<template>
  <NDrawer v-model:show="visible" :width="720" :title="title">
    <NDrawerContent closable>
      <NForm ref="formRef" :model="formModel" :rules="rules" label-placement="left" :label-width="100">
        <NFormItem label="任务名称" path="name">
          <NInput v-model:value="formModel.name" placeholder="请输入任务名称" />
        </NFormItem>
        <NFormItem label="目标表" path="tableName">
          <NInput v-model:value="formModel.tableName" placeholder="请输入目标表名" />
        </NFormItem>
        <NFormItem label="清洗规则" path="ruleIds">
          <NSelect
            v-model:value="formModel.ruleIds"
            multiple
            :options="ruleOptions"
            placeholder="请选择清洗规则"
            filterable
          />
        </NFormItem>
        <NFormItem label="备份数据" path="backupEnabled">
          <NSwitch v-model:value="formModel.backupEnabled" />
          <span class="ml-2 text-gray-500">清洗前是否备份原始数据</span>
        </NFormItem>
        <NFormItem label="调度类型" path="scheduleType">
          <NRadioGroup v-model:value="formModel.scheduleType">
            <NRadio value="MANUAL">手动执行</NRadio>
            <NRadio value="CRON">定时调度</NRadio>
          </NRadioGroup>
        </NFormItem>
        <NFormItem v-if="formModel.scheduleType === 'CRON'" label="Cron表达式" path="cronExpression">
          <NInput v-model:value="formModel.cronExpression" placeholder="请输入Cron表达式，如：0 0 2 * * ?" />
        </NFormItem>
        <NFormItem label="描述" path="description">
          <NInput v-model:value="formModel.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </NFormItem>
        <NFormItem label="状态" path="status">
          <NRadioGroup v-model:value="formModel.status">
            <NRadio :value="1">启用</NRadio>
            <NRadio :value="0">禁用</NRadio>
          </NRadioGroup>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="closeDrawer">取消</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">确定</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch, onMounted } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import { addCleanTask, updateCleanTask, fetchCleanTaskDetail, fetchCleanRuleList } from '@/service/api';

export type ModalType = 'add' | 'edit';

interface Props {
  visible: boolean;
  operateType: ModalType;
  rowData?: { id: number } | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  operateType: 'add',
  rowData: null
});

interface Emits {
  (e: 'update:visible', visible: boolean): void;
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
});

const title = computed(() => (props.operateType === 'add' ? '新增清洗任务' : '编辑清洗任务'));

const formRef = ref<FormInst | null>(null);
const submitLoading = ref(false);
const ruleOptions = ref<Array<{ label: string; value: number }>>([]);

const formModel = reactive({
  id: undefined as number | undefined,
  name: '',
  tableName: '',
  ruleIds: [] as number[],
  backupEnabled: true,
  scheduleType: 'MANUAL',
  cronExpression: '',
  description: '',
  status: 1
});

const rules: FormRules = {
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  tableName: [{ required: true, message: '请输入目标表名', trigger: 'blur' }],
  ruleIds: [{ required: true, type: 'array', message: '请选择清洗规则', trigger: 'change' }],
  scheduleType: [{ required: true, message: '请选择调度类型', trigger: 'change' }],
  cronExpression: [
    {
      required: true,
      message: '请输入Cron表达式',
      trigger: 'blur',
      validator: (rule, value) => {
        if (formModel.scheduleType === 'CRON' && !value) {
          return new Error('请输入Cron表达式');
        }
        return true;
      }
    }
  ]
};

async function loadRules() {
  const res = await fetchCleanRuleList({ pageNum: 1, pageSize: 1000, status: 1 });
  ruleOptions.value = res.data.rows.map((rule: any) => ({
    label: rule.name,
    value: rule.id
  }));
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await formRef.value?.validate();
  submitLoading.value = true;
  try {
    const submitData = {
      ...formModel,
      scheduleConfig: formModel.scheduleType === 'CRON' ? JSON.stringify({ cron: formModel.cronExpression }) : null
    };
    if (props.operateType === 'add') {
      await addCleanTask(submitData);
      window.$message?.success('新增成功');
    } else {
      await updateCleanTask(submitData);
      window.$message?.success('更新成功');
    }
    closeDrawer();
    emit('submitted');
  } finally {
    submitLoading.value = false;
  }
}

async function loadDetail() {
  if (props.operateType === 'edit' && props.rowData?.id) {
    const data = await fetchCleanTaskDetail(props.rowData.id);
    Object.assign(formModel, data.data);
    if (data.data.scheduleConfig) {
      try {
        const config = JSON.parse(data.data.scheduleConfig);
        formModel.cronExpression = config.cron || '';
      } catch (e) {
        console.error('Parse schedule config error:', e);
      }
    }
  }
}

function resetForm() {
  formModel.id = undefined;
  formModel.name = '';
  formModel.tableName = '';
  formModel.ruleIds = [];
  formModel.backupEnabled = true;
  formModel.scheduleType = 'MANUAL';
  formModel.cronExpression = '';
  formModel.description = '';
  formModel.status = 1;
}

watch(visible, val => {
  if (val) {
    loadRules();
    if (props.operateType === 'edit') {
      loadDetail();
    } else {
      resetForm();
    }
  }
});

onMounted(() => {
  loadRules();
});
</script>

<style scoped></style>
